﻿using RestApp.BusinessLogic.Abstract;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RestApp.BusinessLogic
{
	public abstract class BaseLogic<T> : IBaseLogic<T>
		where T : class
	{
		public virtual void Add(T item)
		{
			if(item == null)
			{
				throw new ArgumentNullException("item");
			}

			using(var context = new RestAppEntities())
			{
				var dbSet = context.Set<T>();
				dbSet.Add(item);
				context.SaveChanges();
			}
		}

		public virtual IEnumerable<T> GetAll()
		{
			using(var context = new RestAppEntities())
			{
				return context.Set<T>()
					.AsEnumerable<T>()
					.ToList();
			}
		}

		public virtual void RemoveById(object id)
		{
			if(id == null)
			{
				throw new ArgumentNullException("id");
			}

			using(var context = new RestAppEntities())
			{
				var dbSet = context.Set<T>();
				var entity = dbSet.Find(id);
				dbSet.Remove(entity);
				context.SaveChanges();
			}
		}

		public virtual T GetById(object id)
		{
			if(id == null)
			{
				throw new ArgumentNullException("id");
			}

			using(var context = new RestAppEntities())
			{
				return context.Set<T>().Find(id);
			}
		}

        public void Edit(T entity)
        {
            if (entity == null) throw new ArgumentNullException("entity");
            using(var context = new RestAppEntities())
            {
                var dbSet = context.Set<T>();
                var pKey = dbSet.Create().GetType().GetProperty("Id").GetValue(entity);
                var oldEntity = dbSet.Find(pKey);
                context.Entry<T>(oldEntity).CurrentValues.SetValues(entity);
                context.SaveChanges();
            }
        }
	}
}
